<template>
  <div class="coupons-container">
    <!-- 操作栏 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleCreateTemplate">
        <el-icon><Plus /></el-icon>
        创建优惠券模板
      </el-button>
      <el-input
        v-model="searchQuery"
        placeholder="搜索优惠券"
        style="width: 200px; margin-left: 16px"
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <!-- 优惠券模板列表 -->
    <el-table :data="templates" v-loading="loading" style="width: 100%">
      <el-table-column prop="ID" label="ID" width="80" />
      <el-table-column prop="Name" label="优惠券名称" />
      <el-table-column prop="Type" label="类型" width="120">
        <template #default="{ row }">
          <el-tag :type="row.Type === 'amount' ? 'success' : 'warning'">
            {{ row.Type === 'amount' ? '固定金额' : '折扣比例' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="Value" label="优惠值" width="120">
        <template #default="{ row }">
          {{ row.Type === 'amount' ? `¥${row.Value}` : `${row.Value}%` }}
        </template>
      </el-table-column>
      <el-table-column prop="MinAmount" label="最低使用金额" width="120">
        <template #default="{ row }">
          ¥{{ row.MinAmount }}
        </template>
      </el-table-column>
      <el-table-column prop="ValidDays" label="有效期" width="100">
        <template #default="{ row }">
          {{ row.ValidDays }}天
        </template>
      </el-table-column>
      <el-table-column label="兑换时间" width="280">
        <template #default="{ row }">
          {{ formatDate(row.StartTime) }} 至 {{ formatDate(row.EndTime) }}
        </template>
      </el-table-column>
      <el-table-column label="兑换情况" width="150">
        <template #default="{ row }">
          {{ row.UsedCount }}/{{ row.TotalCount }}
        </template>
      </el-table-column>
      <el-table-column prop="PointsNeeded" label="所需积分" width="100" />
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="{ row }">
          <el-button
            size="small"
            type="info"
            @click="handleViewDetails(row)"
          >
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 创建优惠券模板对话框 -->
    <el-dialog
      v-model="createDialogVisible"
      title="创建优惠券模板"
      width="50%"
    >
      <el-form ref="formRef" :model="templateForm" :rules="rules" label-width="120px">
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="templateForm.name" />
        </el-form-item>
        <el-form-item label="优惠券类型" prop="type">
          <el-select v-model="templateForm.type" style="width: 100%">
            <el-option label="固定金额" value="amount" />
            <el-option label="折扣比例" value="percent" />
          </el-select>
        </el-form-item>
        <el-form-item :label="templateForm.type === 'amount' ? '优惠金额' : '折扣比例'" prop="value">
          <el-input-number 
            v-model="templateForm.value"
            :min="0"
            :precision="templateForm.type === 'amount' ? 2 : 0"
            :max="templateForm.type === 'amount' ? 1000 : 100"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="最低使用金额" prop="min_amount">
          <el-input-number v-model="templateForm.min_amount" :min="0" :precision="2" style="width: 100%" />
        </el-form-item>
        <el-form-item label="有效期天数" prop="valid_days">
          <el-input-number v-model="templateForm.valid_days" :min="1" :max="365" style="width: 100%" />
        </el-form-item>
        <el-form-item label="兑换时间" prop="time_range">
          <el-date-picker
            v-model="templateForm.time_range"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DDTHH:mm:ssZ"
            :shortcuts="dateShortcuts"
            style="width: 100%"
            :teleported="false"
            :editable="false"
            confirm
          />
        </el-form-item>
        <el-form-item label="发放总量" prop="total_count">
          <el-input-number v-model="templateForm.total_count" :min="1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="所需积分" prop="points_needed">
          <el-input-number 
            v-model="templateForm.points_needed" 
            :min="0" 
            style="width: 100%" 
          />
        </el-form-item>
        <el-form-item label="使用说明" prop="description">
          <el-input v-model="templateForm.description" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitTemplate">创建</el-button>
      </template>
    </el-dialog>

    <!-- 优惠券详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="优惠券详情"
      width="50%"
    >
      <template v-if="currentTemplate">
        <div class="template-detail">
          <p><strong>优惠券名称：</strong>{{ currentTemplate.Name }}</p>
          <p><strong>优惠类型：</strong>{{ currentTemplate.Type === 'amount' ? '固定金额' : '折扣比例' }}</p>
          <p><strong>优惠值：</strong>{{ currentTemplate.Type === 'amount' ? `¥${currentTemplate.Value}` : `${currentTemplate.Value}%` }}</p>
          <p><strong>最低使用金额：</strong>¥{{ currentTemplate.MinAmount }}</p>
          <p><strong>有效期：</strong>{{ currentTemplate.ValidDays }}天</p>
          <p><strong>兑换时间：</strong>{{ formatDate(currentTemplate.StartTime) }} 至 {{ formatDate(currentTemplate.EndTime) }}</p>
          <p><strong>兑换情况：</strong>{{ currentTemplate.UsedCount }}/{{ currentTemplate.TotalCount }}</p>
          <p><strong>所需积分：</strong>{{ currentTemplate.PointsNeeded }}</p>
          <p><strong>使用说明：</strong>{{ currentTemplate.Description || '无' }}</p>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import dayjs from 'dayjs'
import { Plus, Search } from '@element-plus/icons-vue'

const store = useStore()
const loading = ref(false)
const templates = ref([])
const searchQuery = ref('')
const createDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const currentTemplate = ref(null)
const formRef = ref<FormInstance>()

// 表单数据
const templateForm = ref({
  name: '',
  type: 'amount',
  value: 0,
  min_amount: 0,
  valid_days: 30,
  time_range: [],
  total_count: 100,
  points_needed: 0,
  description: ''
})

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  }
]

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入优惠券名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择优惠券类型', trigger: 'change' }],
  value: [{ required: true, message: '请输入优惠值', trigger: 'blur' }],
  min_amount: [{ required: true, message: '请输入最低使用金额', trigger: 'blur' }],
  valid_days: [{ required: true, message: '请输入有效期天数', trigger: 'blur' }],
  time_range: [{ required: true, message: '请选择兑换时间', trigger: 'change' }],
  total_count: [{ required: true, message: '请输入发放总量', trigger: 'blur' }],
  points_needed: [{ required: true, message: '请输入所需积分', trigger: 'blur' }]
}

// 加载优惠券模板列表
const loadTemplates = async () => {
  loading.value = true
  try {
    const response = await fetch('http://localhost:8080/api/coupons/templates', {
      headers: {
        'Authorization': `Bearer ${store.state.token}`
      }
    })
    const data = await response.json()
    if (response.ok) {
      templates.value = data.templates
    }
  } catch (error) {
    console.error('Load templates error:', error)
    ElMessage.error('加载优惠券模板失败')
  } finally {
    loading.value = false
  }
}

// 创建优惠券模板
const handleSubmitTemplate = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 确保时间范围已选择
        if (!templateForm.value.time_range || templateForm.value.time_range.length !== 2) {
          ElMessage.warning('请选择兑换时间范围')
          return
        }

        const [startTime, endTime] = templateForm.value.time_range
        const formattedStartTime = dayjs(startTime).format('YYYY-MM-DDTHH:mm:ssZ')
        const formattedEndTime = dayjs(endTime).format('YYYY-MM-DDTHH:mm:ssZ')

        const response = await fetch('http://localhost:8080/api/coupons/templates', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${store.state.token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            name: templateForm.value.name,
            type: templateForm.value.type,
            value: Number(templateForm.value.value),
            min_amount: Number(templateForm.value.min_amount),
            valid_days: Number(templateForm.value.valid_days),
            start_time: formattedStartTime,
            end_time: formattedEndTime,
            total_count: Number(templateForm.value.total_count),
            points_needed: Number(templateForm.value.points_needed),
            description: templateForm.value.description || ''
          })
        })

        const data = await response.json()
        if (response.ok) {
          ElMessage.success('创建优惠券模板成功')
          createDialogVisible.value = false
          loadTemplates()
        } else {
          console.error('Server error:', data.error)
          ElMessage.error(data.error || '创建优惠券模板失败')
        }
      } catch (error) {
        console.error('Create template error:', error)
        ElMessage.error('创建优惠券模板失败')
      }
    }
  })
}

// 查看详情
const handleViewDetails = (template) => {
  currentTemplate.value = template
  detailDialogVisible.value = true
}

// 搜索处理
const handleSearch = () => {
  loadTemplates() // 简单实现，实际可能需要带上搜索参数
}

// 创建模板
const handleCreateTemplate = () => {
  templateForm.value = {
    name: '',
    type: 'amount',
    value: 0,
    min_amount: 0,
    valid_days: 30,
    time_range: [],
    total_count: 100,
    points_needed: 0,
    description: ''
  }
  createDialogVisible.value = true
}

const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

onMounted(() => {
  loadTemplates()
})
</script>

<style scoped>
.coupons-container {
  padding: 20px;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.template-detail {
  padding: 20px;
  line-height: 2;
}

.template-detail p {
  margin: 0;
  border-bottom: 1px solid #eee;
}

.template-detail strong {
  display: inline-block;
  width: 120px;
}
</style> 